package com.ruoyi.web.controller.biz;

import com.ruoyi.biz.domain.ChipInfo;
import com.ruoyi.biz.domain.EquipmentInfo;
import com.ruoyi.biz.domain.SensorInfo;
import com.ruoyi.biz.domain.WarnedRecord;
import com.ruoyi.biz.service.IChipInfoService;
import com.ruoyi.biz.service.IEquipmentInfoService;
import com.ruoyi.biz.service.ISensorInfoService;
import com.ruoyi.biz.service.IWarnedRecordService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.vo.ChartVo;
import com.ruoyi.data.tdengine.domain.Sensor;
import com.ruoyi.data.tdengine.service.SensorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import static com.ruoyi.web.controller.biz.SensorInfoController.getNumberDecimalDigits;

/**
 * 总公司Api
 * docker run -i -t -p 50070:50070 -p 9000:9000 -p 8088:8088 -p 8040:8040 -p 8042:8042  -p 49707:49707  -p 50010:50010  -p 50075:50075  -p 50090:50090 sequenceiq/hadoop-docker:2.6.0 /etc/bootstrap.sh -bash
 */
@RestController
@Api(tags = "总公司Api接口")
@RequestMapping("/company")
public class ApiController {
    @Resource
    private IEquipmentInfoService equipmentInfoService;
    @Resource
    private IWarnedRecordService warnedRecordService;
    @Autowired
    private IChipInfoService chipInfoService;
    @Autowired
    private ISensorInfoService iSensorInfoService;
    @Autowired
    private SensorService sensorService;


    @ApiOperation("告警记录")
    @GetMapping("/select/alarm")
    public List<WarnedRecord> selectAlarmCount(){
        return warnedRecordService.selectWarnedRecordList(new WarnedRecord());
    }


    @ApiOperation("图表选择对应传感器接口,key是各个芯片,value是芯片下的传感器信息")
    @GetMapping("/find/sensor")
    public AjaxResult findSensorData(){
        Map<String,List<SensorInfo>> listMap = new HashMap<>();
        List<ChipInfo> chipInfos = chipInfoService.selectChipInfoList(new ChipInfo());
        chipInfos.forEach(item->{
            if (!listMap.containsKey(item.getChipName())){
                SensorInfo sensorInfo = new SensorInfo();
                sensorInfo.setChipId(item.getChipId());
                List<SensorInfo> sensorInfoList = iSensorInfoService.selectSensorInfoList(sensorInfo);
                listMap.put(item.getChipName(),sensorInfoList);
            }
        });
        return AjaxResult.success(listMap);
    }



    /**
     * 获取图表数据
     * TODO 数据获取还有问题，未解决单一开始/结束时间
     * @return
     */
    @ApiOperation("获取图表数据,用Map结构，ts是时间，value是数据 可以参考 sensor.vue  " +
            "  var orderKanbanMap = new Map();  " +
            "  orderKanbanMap = req  " +
            "  this.TimeData  =  orderKanbanMap[\"ts\"] // 时间数据  " +
            "  this.opinionData = orderKanbanMap[\"value\"]  ")
    @GetMapping("/data/Chart")
    public AjaxResult getChart(ChartVo chartVo){
        List<Sensor> sensorList = new CopyOnWriteArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        List<String> collect = null;
        //数据收集
        Map<String,List> stringListHashMap = new HashMap<>();
        /**
         * 开始时间与结束时间进行细粒度控制
         * 小于一个小时按分钟
         * 大于一个小时小于一天按小时
         * 大于一天按天
         */
        if (chartVo.getPlanBeginTime()==null && chartVo.getPlanEndTime()==null){
            throw new RuntimeException("请选择时间区域");
        }

        Date planBeginTime = chartVo.getPlanBeginTime();
        Date planEndTime = chartVo.getPlanEndTime();
        //时间差
        long time  = planEndTime.getTime() - planBeginTime.getTime();
        long Day = 1000*60*60*24; //天
        long Hour = 1000*60*60; //时
        long minute = 1000*60*5;//分


        try{
            //只有开始时间、或者只有结束时间，或者开始到结束时间大于1天都按该方法
            if (time>Day || chartVo.getPlanEndTime()==null || chartVo.getPlanBeginTime()== null){
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                long endTime = planEndTime.getTime()+ Day;
                chartVo.setPlanEndTime(new Date(endTime));
                sensorList = sensorService.getChart(chartVo.getPlanBeginTime(),chartVo.getPlanEndTime(),chartVo.getSensorCode());
            }else if(time>Hour && time <=Day){
                simpleDateFormat = new SimpleDateFormat("HH:mm");
                long endTime = planEndTime.getTime()+ Hour;
                chartVo.setPlanEndTime(new Date(endTime));
                sensorList = sensorService.getChartByHour(chartVo.getPlanBeginTime(),chartVo.getPlanEndTime(),chartVo.getSensorCode());
            }else {
                simpleDateFormat = new SimpleDateFormat("HH:mm");
                long endTime = planEndTime.getTime()+minute;
                chartVo.setPlanEndTime(new Date(endTime));
                sensorList = sensorService.getChartMinute(chartVo.getPlanBeginTime(),chartVo.getPlanEndTime(),chartVo.getSensorCode());
            }
        }catch (Exception e){
            throw new RuntimeException("该传感器无数据");
        }



        SimpleDateFormat finalSimpleDateFormat = simpleDateFormat;
        collect = sensorList.stream().map(item -> {
            Timestamp ts = item.getTs();
            return finalSimpleDateFormat.format(ts);
        }).collect(Collectors.toList());

        /**
         * 依据精度进行处理 78.439  精度 0.1   78.4
         */
        SensorInfo sensorInfo = iSensorInfoService.selectSensorByCode(chartVo.getSensorCode());
        String rule = getNumberDecimalDigits(sensorInfo.getAccuracy());
        List<Double> doubles = sensorList.stream().map(item->{
            DecimalFormat df = new DecimalFormat(rule);
            String str = df.format(item.getValue());
            return Double.valueOf(str);
        }).collect(Collectors.toList());

        stringListHashMap.put("ts",collect);
        stringListHashMap.put("value",doubles);
        return AjaxResult.success(stringListHashMap);
    }

}
